﻿using AutoMapper;
using B.S.GridManager.Api.Read.Application.Command.LogicalGrid;
using B.S.GridManager.Api.Read.Dtos;
using B.S.GridManager.ErrorCode;
using B.S.GridManager.Infrastructure.Interface;
using B.S.GridManger.Domain.Entities;
using MediatR;

namespace B.S.GridManager.Api.Read.Application.CommandHandler.LogicalGrid
{
    public class GetLogicalGridTreeHandler : IRequestHandler<GetLogicalGridTreeCommand, ApiResult<List<LogicalGridTreeDTO>>>
    {
        private readonly IBaseRepository<LogicGridModel> logicalRepo;
        private readonly IMapper mapper;

        public GetLogicalGridTreeHandler(IBaseRepository<LogicGridModel> logicalRepo,IMapper mapper)
        {
            this.logicalRepo = logicalRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<List<LogicalGridTreeDTO>>> Handle(GetLogicalGridTreeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<LogicalGridTreeDTO>> result = new ApiResult<List<LogicalGridTreeDTO>>();
            result.Data = getTree(642046226423813);

            result.Code = ApiEnums.Success;
            result.Msg = "递归查找所有逻辑网格数据成功!";
            return Task.FromResult(result);
        }

        private List<LogicalGridTreeDTO> getTree(long parentId)
        {
            var logics = logicalRepo.GetAll().Where(x => x.ParentId == parentId);
            var logicdtos = mapper.Map<List<LogicalGridTreeDTO>>(logics);
            foreach (var item in logicdtos)
            {
                item.Children = getTree(item.Id);
            }

            return logicdtos;
        }
    }
}
